package com.example.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.example.entity.URLEntity;

public class URLParser {
	public static final String pattern = "^([^:]+)\\://([a-zA-Z0-9\\-\\.]+)\\.([a-zA-Z]{2,3})(/\\S*)?$";
	public static Pattern urlPattern = Pattern.compile(pattern);
	
	public static URLEntity parse(String url) {
		URLEntity request = new URLEntity();
		Matcher m = urlPattern.matcher(url);
		if (m.find()) {
			try {
				request.setUrl(m.group(0));	
			}
			catch (Exception e) {}
			
			try {
				request.setProtocol(m.group(1));	
			}
			catch (Exception e) {}
			
			String domainPrefix = "";
			String domainHost = "";
			try {
				String domain = m.group(2);
				request.setDomain(domain);
				int index = domain.indexOf('.');
				if (index > 0) {
					domainPrefix = domain.substring(0, index);
					domainHost = domain.substring(index + 1);
				}
				else
					domainHost = domain;
			}
			catch (Exception e) {}
			
			try {
				request.setDomainPrefix(domainPrefix);	
			}
			catch (Exception e) {}
			
			try {
				request.setDomainHost(domainHost);	
			}
			catch (Exception e) {}
			
			try {
				request.setDomainExtension(m.group(3));	
			}
			catch (Exception e) {}
			
			try {
				request.setUri(m.group(4));	
			}
			catch (Exception e) {}
	    }
		
		return request;
	}
}
